package ui

import (
	"gitallpush/config"

	"github.com/lxn/walk"
)

type ConfigModel struct {
	walk.TableModelBase
	configs []config.GitConfig
	view    *walk.TableView
}

func NewConfigModel(configs []config.GitConfig) *ConfigModel {
	return &ConfigModel{configs: configs}
}

func (m *ConfigModel) SetView(view *walk.TableView) {
	m.view = view
}

func (m *ConfigModel) RowCount() int {
	return len(m.configs)
}

func (m *ConfigModel) Value(row, col int) interface{} {
	cfg := m.configs[row]
	switch col {
	case 0:
		return cfg.Enabled
	case 1:
		return cfg.Group
	case 2:
		return cfg.Platform
	case 3:
		return cfg.RepoURL
	case 4:
		return cfg.Branch
	}
	return nil
}

func (m *ConfigModel) SetValue(row, col int, value interface{}) error {
	if col == 0 {
		m.configs[row].Enabled = value.(bool)
		config.SaveConfig(m.configs)
	}
	return nil
}

func (m *ConfigModel) FilterByGroup(group string) {
	if group == "" {
		return
	}

	filtered := make([]config.GitConfig, 0)
	for _, cfg := range m.configs {
		if cfg.Group == group {
			filtered = append(filtered, cfg)
		}
	}
	m.configs = filtered
	m.view.SetModel(m)
}

// Configs 返回当前的配置列表
func (m *ConfigModel) Configs() []config.GitConfig {
	return m.configs
}

// SetConfigs 设置新的配置列表
func (m *ConfigModel) SetConfigs(configs []config.GitConfig) {
	m.configs = configs
}
